{-# LANGUAGE OverloadedStrings#-}
{-# LANGUAGE ScopedTypeVariables#-}
{-# LANGUAGE RecordWildCards,DeriveGeneric#-}

module App.SNSMessage.Core (postMessage,queryMessage) where
import App.Common.Types
import qualified Data.Text as T
import qualified Data.Time as DT
import Data.Int
import App.UserCenter.Core
import GHC.Generics (Generic)
import Control.Monad.Trans.Except
import Control.Monad.Trans
import Data.Either.Utils
import App.SNSMessage.DB
import Database.Persist
import Database.Persist.Sqlite
import App.Common.Table
import Data.Aeson

instance ToJSON Message

postMessage::(WebAppM m) => T.Text -> Int64 -> Int64 -> m (Either T.Text Int64)
postMessage context reblogId replyId = runExceptT $ do
  userId <- maybeToEither "没有登录" =<< lift getLoginUserId
  now <- liftIO  DT.getCurrentTime
  rPlyUid <- if (replyId/=(-1)) then do
                  eMsg <- lift (getMessage replyId)
                  msg <- eitherToMonadError eMsg
                  return $ messageAccountId msg
             else return (-1)
  let insertMsg = Message {
    messageText             = context,
    messageSpoilerText      = context,
    messageAccountId        = userId,
    messageCreateTime       = now,
    messageReblogOfId       = reblogId,
    messageReplyToId        =  replyId,
    messageReplyToAccountId =  rPlyUid,
    messageVisibility       = Show
  }
  key <- lift.runDB.insert $ insertMsg
  return.fromSqlKey $ key

getMessage::(WebAppM m) => Int64 -> m (Either T.Text Message)
getMessage msgId = runExceptT $ do
  mayMsg::Maybe Message <- lift.runDB.get.toSqlKey $ msgId
  maybeToEither "不存在的信息" mayMsg

em2tp::Entity Message -> (Int64,Message)
em2tp (Entity k v) = (fromSqlKey  k,v)

filterUserId::Maybe Int64 -> [Filter Message]
filterUserId Nothing = []
filterUserId (Just uid) = [MessageAccountId==.uid]

queryMessage::(WebAppM m) => Maybe Int64 -> PageInfo -> [Filter Message] -> m (Table (Int64,Message))
queryMessage mayUserId pi@(PageInfo cp ps) flist = do
  msgCount <- runDB $ count (flist::[Filter Message])
  msgList::[Entity Message] <- runDB $ selectList (filterUserId mayUserId <> flist) [LimitTo ps,OffsetBy (cp * ps),Desc MessageCreateTime]
  return $ Table {total = msgCount,pageInfo = pi,tableData = (map em2tp msgList)}

